package com.teacher.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.common.ResultCode;
import com.teacher.mapper.PerStudentMapper;
import com.teacher.mapper.PerTeacherMapper;
import com.teacher.mapper.TermMapper;
import com.teacher.pojo.dto.file.FileAddDto;
import com.teacher.pojo.dto.publicwelfareactivitiestask.PublicWelfareActivitiesTaskAddDto;
import com.teacher.pojo.dto.publicwelfareactivitiestask.PublicWelfareActivitiesTaskUpdateDto;
import com.teacher.pojo.entity.Flow;
import com.teacher.pojo.entity.PublicWelfareActivitiesTask;
import com.teacher.mapper.PublicWelfareActivitiesTaskMapper;
import com.teacher.pojo.enums.FlowApproveType;
import com.teacher.pojo.enums.FlowType;
import com.teacher.pojo.vo.publicwelfareactivitiestask.PublicWelfareActivitiesTaskGetVo;
import com.teacher.service.IFlowService;
import com.teacher.service.IPublicWelfareActivitiesTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 公益活动-一条0.5 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-08-11
 */
@Service
public class PublicWelfareActivitiesTaskServiceImpl extends ServiceImpl<PublicWelfareActivitiesTaskMapper, PublicWelfareActivitiesTask> implements IPublicWelfareActivitiesTaskService {
    @Autowired
    private IFlowService iFlowService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PerTeacherMapper perTeacherMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private TermMapper termMapper;

    @Autowired
    private PerStudentMapper perStudentMapper;

    /**
     * 发起公益活动
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<String> add(PublicWelfareActivitiesTaskAddDto dto) {
        String studentKey = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        if (studentKey == null) {
            return CommonResult.failed("非法用户");
        }
        String monitorKey = perTeacherMapper.getMonitorByStudentKey(studentKey);
        if (StrUtil.isEmpty(monitorKey)) {
            return CommonResult.failed("未找到下一节审批人");
        }

        Long flowId = iFlowService.createFlow(studentKey, monitorKey, FlowType.PUBLIC_WELFARE_ACTIVITIES.getType());

        if (flowId == null) {
            return CommonResult.failed("启动失败");
        }
        PublicWelfareActivitiesTask publicWelfareActivitiesTask = new PublicWelfareActivitiesTask();
        BeanUtils.copyProperties(dto, publicWelfareActivitiesTask);
        publicWelfareActivitiesTask.setFlowId(flowId);
        publicWelfareActivitiesTask.setFiles(JSONUtil.toJsonStr(dto.getFiles()));
        publicWelfareActivitiesTask.setTermId(termMapper.getCurrentTerm());
        publicWelfareActivitiesTask.setStudentKey(jwtTokenUtil.getUsernameByRequest(httpServletRequest));
        if (this.save(publicWelfareActivitiesTask)) {
            return CommonResult.success("提交成功");
        }
        return CommonResult.failed("提交失败");
    }

    /**
     * 更新流程
     *
     * @param dto
     * @return
     */
    @Override
    public CommonResult<String> updateInfo(PublicWelfareActivitiesTaskUpdateDto dto) {
        CommonResult<String> result = iFlowService.reStart(dto.getId());
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            return result;
        }
        PublicWelfareActivitiesTask publicWelfareActivitiesTask = this.getOne(new QueryWrapper<PublicWelfareActivitiesTask>().lambda()
                .eq(PublicWelfareActivitiesTask::getFlowId, dto.getId()).last("limit 1"));
        publicWelfareActivitiesTask.setRemark(dto.getRemark());
        publicWelfareActivitiesTask.setFiles(JSONUtil.toJsonStr(dto.getFiles()));
        publicWelfareActivitiesTask.setTitle(dto.getTitle());
        if (this.updateById(publicWelfareActivitiesTask)) {
            return CommonResult.success("提交成功");
        }
        return CommonResult.failed("提交失败");
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<PublicWelfareActivitiesTaskGetVo> getDetails(Long id) {
        PublicWelfareActivitiesTask publicWelfareActivitiesTask = this.getOne(new QueryWrapper<PublicWelfareActivitiesTask>().lambda()
                .eq(PublicWelfareActivitiesTask::getFlowId, id));
        if (publicWelfareActivitiesTask == null) {
            return CommonResult.failed("流程不存在");
        }
        PublicWelfareActivitiesTaskGetVo vo = new PublicWelfareActivitiesTaskGetVo();
        BeanUtils.copyProperties(publicWelfareActivitiesTask, vo);
        vo.setFiles(JSONUtil.toList(JSONUtil.parseArray(publicWelfareActivitiesTask.getFiles()), FileAddDto.class));
        vo.setFlowApproveDetailsVos(iFlowService.getApproveDetails(id));
        vo.setStudentName(perStudentMapper.getNameByStudentKey(publicWelfareActivitiesTask.getStudentKey()));
        vo.setCreateTime(publicWelfareActivitiesTask.getCreateTime());
        Flow flow = iFlowService.getById(id);
        // 是否可取消
        if (flow.getApplyUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))
                && flow.getStatus().equals(FlowApproveType.WAIT.getCode())) {
            vo.setCanCancel(true);
        } else {
            vo.setCanCancel(false);
        }
        // 是否可审批
        if (flow.getCurrentApproveUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))) {
            vo.setCanApprove(true);
        } else {
            vo.setCanApprove(false);
        }
        // 是否可重新提交
        if (flow.getApplyUsername().equals(jwtTokenUtil.getUsernameByRequest(httpServletRequest))
                && flow.getStatus().equals(FlowApproveType.BACK_UPDATE.getCode())) {
            vo.setCanBack(true);
        } else {
            vo.setCanBack(false);
        }
        return CommonResult.success(vo);
    }
}
